package com.mediacloud.app.newsmodule.fragment.nav2;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mediacloud.app.fbnavsk.SecondFloorHandlerKt;
import com.mediacloud.app.fbnavsk.SecondNav;
import com.mediacloud.app.nav2.fragment.HqyNavFragment;
import com.mediacloud.app.view.XSmartRefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.mediacloud.app.model.activity.FragmentActivityBase;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.view.AppfacHeaderAndFooterContainer;
import com.mediacloud.app.model.view.RecyclerViewHF;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter;
import com.mediacloud.app.newsmodule.view.ComponentContainer;
import com.mediacloud.app.newsmodule.view.LocationChooseHeader;
import com.mediacloud.app.reslib.enums.Navigate;
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop;
import com.tencent.qcloud.tim.uikit.utils.MD5Utils;

import java.util.ArrayList;
import java.util.List;

import static com.mediacloud.app.nav2.fragment.HqyNavFragmentKt.FLAG_SCROLL_POSITION;
import static com.mediacloud.app.nav2.fragment.HqyNavFragmentKt.FLAG_SCROLL_TOP;


/**
 * Created by hello-world on 2018/5/11.
 */

public abstract class BaseRecyclerListFragment<T extends BaseRecyclerAdapter> extends HqyNavFragment implements OnRefreshLoadMoreListener,ToolBarActionF5OrTop {
    protected RecyclerViewHF recyclerView;
    protected CatalogItem catalogItem;
    protected View sohuHeaderView;
    protected LinearLayout headerViewContainer;
    protected String catalogID;
    protected int pageIndex = 1;
    protected int perPageSize = 20;
    protected XSmartRefreshLayout refreshLayout;
    protected TextView emptyTipsText;
    /**
     * 组件的
     */
    protected ComponentContainer componetContainer;

    protected T recyclerAdapter;
    /**
     * 上一次滚动停留的位置
     * */
    private int lastSelectedPosition;
    /**
     * 上一次滚动位置的偏差
     * */
    protected int lastSelectedPositionOffset = 0;

    @Override
    public int getLayoutResID()
    {
        return R.layout.fragment_baserecyclerlist;
    }



    public abstract  T getRecyclerAdapter();

    public abstract RecyclerView.LayoutManager getLayoutManager();

    @CallSuper
    @Override
    protected void initArgs()
    {
        super.initArgs();
        if (getFragmentArguments() != null) {
            saveInstanceArguments = getFragmentArguments();
            catalogID = saveInstanceArguments.getString("id");
            catalogItem = saveInstanceArguments.getParcelable("catalog");
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments.getString("id");
            catalogItem = saveInstanceArguments.getParcelable("catalog");
        }
        if(catalogItem==null)
            catalogItem=new CatalogItem();
    }

    protected void initComponentContainer()
    {
        headerViewContainer = new AppfacHeaderAndFooterContainer(getActivity());
        headerViewContainer.setOrientation(LinearLayout.VERTICAL);
        componetContainer = new ComponentContainer(getActivity(),getCurrentICMP26Holder());
        componetContainer.componentListItemStyleAdaptor.catalogItem = catalogItem;
        headerViewContainer.addView(componetContainer);
/*        componetContainer = new ComponentContainer(getActivity());
        componetContainer.componentListItemStyleAdaptor.catalogItem = catalogItem;
        headerViewContainer.addView(componetContainer);*/
    }

    private int begin_position=0;
    private int stop_position=0;
    @CallSuper
    @Override
    public void initView()
    {
        refreshLayout=mRootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        emptyTipsText=mRootView.findViewById(R.id.emptyTipsText);
        loadingView = mRootView.findViewById(R.id.mLoadingView);
        initStateView();
        showStateView(TYPE_LOADING, false);
        recyclerView = mRootView.findViewById(R.id.recyclerView);
        recyclerView.setBackgroundColor(Color.WHITE);
        recyclerView.setLayoutManager(getLayoutManager());
        recyclerAdapter=getRecyclerAdapter();
        recyclerView.setAdapter(recyclerAdapter);
        addLBSChosoeHeader();
        initComponentContainer();
        if(getNavigate()!=null&&getNavigate().getSpecial_effect()==1){
            sohuHeaderView = LayoutInflater.from(getActivity()).inflate(R.layout.sohu_top_sign,null,false);
            recyclerView.addHeaderView(sohuHeaderView);
        }
        recyclerView.addHeaderView(headerViewContainer);
        componetContainer.setRecyclerView(this.recyclerView);
        componetContainer.setRootView(mRootView);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int currentScrollY;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                int scrollOffset = recyclerView.computeVerticalScrollOffset();
                Log.w(TAG,"onScrollStateChanged :: "+newState+ " scrollOffset :: "+scrollOffset+"  recyclerView height :: "+recyclerView.getMeasuredHeight());
                super.onScrollStateChanged(recyclerView, newState);
                if(RecyclerView.SCROLL_STATE_IDLE == newState){
                    if(scrollOffset > recyclerView.getMeasuredHeight() && !hasScrollerFlag(FLAG_SCROLL_POSITION)){
                        setScrollerFlag(FLAG_SCROLL_POSITION);
                    }else if(scrollOffset < recyclerView.getMeasuredHeight() && scrollOffset > 0 && !hasScrollerFlag(FLAG_SCROLL_TOP)){
                        setScrollerFlag(FLAG_SCROLL_TOP);
                    }else if(scrollOffset == 0){
                        setScrollerFlag(FLAG_SCROLL_TOP);
                    }
                    stop_position=Math.abs(currentScrollY);
                    if (catalogItem!=null) {
                        begin_position=stop_position;
                    }
                }
                //判断ListView是否滑动到第一个Item的顶部
                if (refreshLayout != null && recyclerView.getChildCount() > 0 && lastSelectedPosition == 0
                        && recyclerView.getChildAt(0).getTop() >= recyclerView.getPaddingTop()) {
                    //解决滑动冲突，当滑动到第一个item，下拉刷新才起作用
                    refreshLayout.setEnableRefresh(true);
                } else {
                    refreshLayout.setEnableRefresh(false);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                currentScrollY += dy;
            }
        });
    }

    protected void addComponent(List<ComponentItem> componentItemList)
    {
        if(componentItemList==null||componentItemList.size()==0)
        {
            componetContainer.clearOld();
            return;
        }
        ArrayList<ComponentItem> data=new ArrayList<>();
        data.addAll(componentItemList);
        componetContainer.updateComponent(data);
    }
    @CallSuper
    protected void addLBSChosoeHeader()
    {
        //LBS栏目不为空就加上头
        if (catalogItem != null && catalogItem.getLbsItem() != null)
        {
            int maxLBSH = getActivity().getResources().getDimensionPixelSize(R.dimen.dime_fifty);
            LocationChooseHeader locationChooseHeader = new LocationChooseHeader(getActivity());
            locationChooseHeader.catalogItem = catalogItem;
            locationChooseHeader.tag = FGTag.TagID;
            locationChooseHeader.setVisiableHeight(maxLBSH);
            recyclerView.addHeaderView(locationChooseHeader);
        }
    }


    @CallSuper
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView.setVerticalScrollBarEnabled(false);
        recyclerView.setHorizontalScrollBarEnabled(false);
        if(hadChoosed)
        {
            SecondFloorHandlerKt.initFStyle(this,refreshLayout,recyclerView);
        }
        else
        {
            SecondFloorHandlerKt.navPaddingTopMatch(this);
        }
        Navigate navigateArgs=(catalogItem!= null&&catalogItem.getNavigate()!=null)?catalogItem.getNavigate():super.getNavigate();
        setNavigate(navigateArgs);
        setRefreshLayoutColor(refreshLayout,navigateArgs);
    }

    @Override
    public final void f5() {
        recyclerView.scrollToPosition(0);
        refreshLayout.autoRefresh(200);
    }

    @Override
    public final void gun()
    {
        setScrollParams();
        setScrollerFlag(FLAG_SCROLL_TOP);
        recyclerView.scrollToPosition(0);
    }

    @Override
    public boolean handleScroller() {
        if(hasScrollerFlag(FLAG_SCROLL_TOP)){
            setScrollerFlag(FLAG_SCROLL_POSITION);

            RecyclerView.LayoutManager layoutManager =  recyclerView.getLayoutManager();
            if(layoutManager instanceof  LinearLayoutManager){
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                linearLayoutManager.scrollToPositionWithOffset(lastSelectedPosition,lastSelectedPositionOffset);
            }
//            recyclerView.scrollToPosition(lastSelectedPosition);
//            recyclerView.scrollBy(0,lastSelectedPositionOffset);
            return true;
        }
        if(hasScrollerFlag(FLAG_SCROLL_POSITION)){
            setScrollerFlag(FLAG_SCROLL_TOP);
            setScrollParams();
            refreshLayout.getRefreshKernel().moveSpinner(0,false);
            recyclerView.requestFocusFromTouch();
            recyclerView.scrollToPosition(0);
            return true;
        }
        return true;
    }

    private void setScrollParams(){
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if(manager instanceof LinearLayoutManager){
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) manager;
            lastSelectedPosition = linearLayoutManager.findFirstVisibleItemPosition();
            View view = linearLayoutManager.findViewByPosition(lastSelectedPosition);
            if(view != null){
                lastSelectedPositionOffset = view.getTop();
            }

        }
    }

    protected void startActivity(Context context, Intent intent) {
        if (context instanceof FragmentActivityBase) {
            FragmentActivityBase activityBase = (FragmentActivityBase) context;
            activityBase.startActivity(intent, false);
        } else {
            context.startActivity(intent);
        }
    }

    @Override
    public void choosed() {
        super.choosed();
        if(getActivity()!=null)
        {
            mRootView.post(()->{
                SecondFloorHandlerKt.initFStyle(this,refreshLayout,sohuHeaderView);
            });
        }
        showBottomDivide();
    }

    protected void showBottomDivide(){
        Fragment fragment = getRootFragment();
        if(fragment instanceof SecondNav){
            SecondNav secondNav = (SecondNav) fragment;
            try {
                //1 2 代表新浪和搜狐的二楼效果 参考的SecondFloorHandler.kt
                if(getNavigate()!= null &&
                (getNavigate().getSpecial_effect() == 1 || getNavigate().getSpecial_effect() == 2)
                        && secondNav.getSecondTabIsNotOnToolBar()){
                    secondNav.setTableBottomDivideVisible(false);
                }else {
                    secondNav.setTableBottomDivideVisible(true);
                }
            }catch (Exception e){
                e.printStackTrace();
                secondNav.setTableBottomDivideVisible(true);
            }
        }
    }

    @Override
    public void onDestroyView() {
        if (componetContainer != null) {
            componetContainer.dispose();
            componetContainer = null;
        }
        super.onDestroyView();
    }
}